package com.futao.springsecuritylearn.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.futao.springsecuritylearn.entity.UserEntity;
import com.futao.springsecuritylearn.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ft
 * @date 2021/5/18
 */
@Service
public class UserService implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userMapper.selectOne(Wrappers.<UserEntity>lambdaQuery()
                .eq(UserEntity::getUsername, username)
        );
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        List<GrantedAuthority> roles = AuthorityUtils.commaSeparatedStringToAuthorityList(userEntity.getRole());
        return new User(userEntity.getUsername(), new BCryptPasswordEncoder().encode(userEntity.getPassword()), roles);
    }
}
